package com.atguigu.hbase;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Created by 黄凯 on 2023/6/30 0030 18:59
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class HBase03_DDL {

    public static Connection connection = Hbase02_SingletonConnection.getConnection();



    public static void main(String[] args) throws IOException {

        testCreateTable("" , "emp" , "f1" , "f2");

    }

    /**
     * 作业(可选)
     * 修改表   Admin.modifyTable()
     * 删除表   Admin.deleteTable()
     * 创建namespace  Admin.createNamespace()
     * 修改namespace  Admin.modifyNamespace()
     * 删除namespace  Admin.deleteNamespace()
     */



    /**
     *  创建表
     *  Shell: create 'namespaceName:tableName' , 'cf...'
     */
    public static void testCreateTable(String namespaceName, String tableName, String ... cfs  ) throws IOException {

        //基本的判空处理。
        //namespace如果为null ，默认使用default
        if(tableName == null || tableName.equals("")){
            System.out.println("表名不能为空.");
            return ;
        }
        if(cfs == null || cfs.length == 0){
            System.out.println("至少要指定一个列族.");
            return ;
        }

        //基于connection获取Admin对象
        Admin admin = connection.getAdmin();

        TableName tableName1 = TableName.valueOf(namespaceName,tableName);

        //判断表是否存在
        boolean tableExists = admin.tableExists(tableName1);

        if (tableExists){

            System.out.println( ( (namespaceName == null || namespaceName.equals("")) ? "default": namespaceName ) + ":" + tableName + " 已经存在!");
            return ;

        }

        //建表操作
        TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName1);

        //设置列族
        for (String cf : cfs) {

            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(cf));

            ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptorBuilder.build();

            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);

        }

        TableDescriptor tableDescriptor = tableDescriptorBuilder.build();


        admin.createTable(tableDescriptor);

        System.out.println( ( (namespaceName == null || namespaceName.equals("")) ? "default": namespaceName ) + ":" + tableName + " 创建成功!");

        admin.close();


    }

}
